﻿using Account;
using Account.Input;
using Account.Output;
using Bridge.Shared.Helper;
using Bridge.Shared.Models;
using Bridge.Shared.Redis;
using Lazy.Captcha.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;

namespace Bridge.System.HttpApi
{
    [Route("UserAccount")]
    public class UserAccountController : AbpController
    {
        private readonly IUserAccountService _userAccountService;
        private readonly ICaptcha SecurityCodeHelper;
        private readonly IConfiguration _config;
        private readonly ICacheManager _cacheManager;
        public UserAccountController(IUserAccountService userAccountService, ICaptcha captcha, IConfiguration config, ICacheManager cacheManager)
        {
            _userAccountService = userAccountService;
            SecurityCodeHelper = captcha;
            _config = config;
            _cacheManager = cacheManager;
        }

        [HttpPost]
        [Route("login")]
        [AllowAnonymous]
        public async Task<ResponseResult<LoginOutput>> Login([FromBody] LoginInput login)
        {
            try
            {
                var validCode = SecurityCodeHelper.Validate(login.Uuid, login.Code);

                if (_config["CaptchaOptions:CaptchaOnOff"] != "off" && !validCode)
                {
                    return ResponseResult<LoginOutput>.Fail("验证码错误！");
                }
                return await _userAccountService.Login(login);
            }
            catch (Exception ex)
            {
                return ResponseResult<LoginOutput>.Fail(ex.Message);
            }
        }
        [HttpPost]
        [Route("loginOut")]
        public async Task<ResponseResult> LoginOut()
        {
            try
            {
                return await _userAccountService.LoginOut();
            }
            catch (Exception ex)
            {
                return ResponseResult<LoginOutput>.Fail(ex.Message);
            }
        }
        [HttpPost]
        [Route("ssologin")]
        [AllowAnonymous]
        public async Task<ResponseResult<LoginOutput>> SSOLogin([FromBody] LoginInput login)
        {
            try
            {
                return await _userAccountService.SSOLogin(login);
            }
            catch (Exception ex)
            {
                return ResponseResult<LoginOutput>.Fail(ex.Message);
            }
        }
        [HttpPost]
        [Route("phoneLogin")]
        [AllowAnonymous]
        public async Task<ResponseResult<LoginOutput>> PhoneLogin([FromBody] PhoneLoginInput login)
        {
            try
            {
                //1、校验验证码
                var validCode = SecurityCodeHelper.Validate(login.Uuid, login.Code);

                if (_config["CaptchaOptions:CaptchaOnOff"] == "on" && !validCode)
                {
                    return ResponseResult<LoginOutput>.Fail("验证码错误！");
                }

                //2、校验手机号
                string phoneCode = await _cacheManager.GetAsync<string>(login.PhoneNumber);

                if (phoneCode == null)
                {
                    return ResponseResult<LoginOutput>.Fail("手机验证码错误！");
                }
                return await _userAccountService.PhoneLogin(login);
            }
            catch (Exception ex)
            {
                return ResponseResult<LoginOutput>.Fail(ex.Message);
            }
        }
        [HttpGet]
        [Route("captchaImage")]
        [AllowAnonymous]
        public async Task<ResponseResult<object>> CaptchaImage()
        {
            try
            {
                string uuid = Guid.NewGuid().ToString().Replace("-", "");
                var info = SecurityCodeHelper.Generate(uuid, 60);
                var captchaOff = "0";
                return ResponseResult<object>.Success("ok", new { captchaOff, uuid, img = info.Base64 });

            }
            catch (Exception ex)
            {
                return ResponseResult<object>.Fail(ex.Message);
            }
        }
        //[HttpGet("/GenerateQrcode")]
        [HttpGet]
        [Route("GenerateQrcode")]
        [AllowAnonymous]
        public async Task<ResponseResult<object>> GenerateQrcode(string uuid, string deviceId)
        {
            try
            {
                var state = Guid.NewGuid().ToString();
                var dict = new Dictionary<string, object>
            {
                { "state", state }
            };

                return ResponseResult<object>.Success("操作成功！", new
                {
                    status = 1,
                    state,
                    uuid,
                    codeContent = new { uuid, deviceId }// "https://qm.qq.com/cgi-bin/qm/qr?k=kgt4HsckdljU0VM-0kxND6d_igmfuPlL&authKey=r55YUbruiKQ5iwC/folG7KLCmZ++Y4rQVgNlvLbUniUMkbk24Y9+zNuOmOnjAjRc&noverify=0"
                });

            }
            catch (Exception ex)
            {
                return ResponseResult<object>.Fail(ex.Message);
            }
        }

        /// <summary>
        /// 发送smsCode
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SendSmsCode")]
        [AllowAnonymous]
        public async Task<ResponseResult> SendSmsCode([FromBody] SendSmsCodeInput input)
        {
            var validCode = SecurityCodeHelper.Validate(input.Uuid, input.Code);
            //1、校验验证码
            if (_config["CaptchaOptions:CaptchaOnOff"]=="on" && !validCode)
            {
                return ResponseResult.Fail("验证码错误！");
            }

            //2、发送验证码
            var smsCode = RandomHelper.GenerateNum(6);
            var smsContent = $"验证码{smsCode}（随机验证码）,有效期10分钟。";

            //3、写入到缓存中
           await   _cacheManager.AddAsync(input.PhoneNum, smsCode, TimeSpan.FromSeconds(10));
            return ResponseResult.Success(smsContent);
        }



    }
}
